//
// Created by daiyizheng on 2022/3/27.
//
#include <iostream>

using namespace std;
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
            : val(_val), left(_left), right(_right), next(_next) {}
};

// BFS 层序遍历
#include <queue>
Node* connect(Node* root) {
    if(!root)return nullptr;
    queue<Node*> qe;
    qe.push(root);
    while (!qe.empty()){
        int size = qe.size();
        for (int i = 0; i < size; ++i) {
            Node *currNode = qe.front();
            qe.pop();
            if(i!=size-1)currNode->next = qe.front();
            if(currNode->left)qe.push(currNode->left);
            if(currNode->right)qe.push(currNode->right);
        }
    }
    return root;
}